<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>JS Reference VS Copy</title>
</head>

<body>

  <script>
    // start with strings, numbers and booleans
    let num = 1
    let num2 = num1
    console.log(num, num1)
    num = 3
    console.log(num.num2)
    // Let's say we have an array
    const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];

    // and we want to make a copy of it.
    const team = players
    // You might think we can just do something like this:
    players.pop()
    // however what happens when we update that array?
    console.log(players)
    // now here is the problem!
    console.log(team)
    // oh no - we have edited the original array too!

    // Why? It's because that is an array reference, not an array copy. They both point to the same array!

    // So, how do we fix this? We take a copy instead!

    // one way
    const team1 = className.slice()

    // or create a new array and concat the old one in
    const team2 = [].concat(className)
    // or use the new ES6 Spread
    const team3 = [...className]
    const team4 = Array.from(className)
    // now when we update it, the original one isn't changed
    console.log(team1)
    className.pop()
    console.log(team1)
    // The same thing goes for objects, let's say we have a person object

    // with Objects
    const person = {
      name: 'Wes Bos',
      age: 80
    };

    // and think we make a copy:
    const cap = person
    cap.age = 55
    console.log(person, cap)
    // how do we take a copy instead?
    const cap2 = Object.assign({}, person)
    cap2.age = 44
    console.log(person, cap2)
    // We will hopefully soon see the object ...spread
    const cap4 = {
      ...person
    }
    // Things to note - this is only 1 level deep - both for Arrays and Objects. lodash has a cloneDeep method, but you should think twice before using it.
    const cap3 = JSON.parse(JSON.stringify(person))
    cap3.age = 22
    console.log(person, cap3)
  </script>

</body>

</html>